// #ifdef XT_PC || H5
import TRTC from 'trtc-js-sdk'
// #endif
// #ifdef MP-WEIXIN
import TRTCWX from 'trtc-wx-sdk'
// #endif
// #ifdef APP-PLUS
import TrtcApp from "./TrtcApp/lib/index"
import { TRTCAppScene, TRTCRoleType, TRTCVideoStreamType } from './TrtcApp/lib/TrtcDefines'
console.log('xone-trtc init', TrtcApp)
// #endif

// import { TRTCAppScene, TRTCRoleType, TRTCVideoStreamType } from './TrtcApp/lib/TrtcDefines'

// https://cloud.tencent.com/document/product/647/49327

const logkey = 'xone-trtc'

let trtc = {
  // #ifdef MP-WEIXIN
  bindTRTCRoomEvent(page) {
    const TRTC_EVENT = this.trtc.EVENT;
    // 初始化事件订阅
    this.trtc.on(TRTC_EVENT.LOCAL_JOIN, event => {
      console.log(logkey, '* room LOCAL_JOIN', event);
    });
    this.trtc.on(TRTC_EVENT.LOCAL_LEAVE, event => {
      console.log(logkey, '* room LOCAL_LEAVE', event);
    });
    this.trtc.on(TRTC_EVENT.ERROR, event => {
      console.log(logkey, '* room ERROR', event);
    });
    // 远端用户退出
    this.trtc.on(TRTC_EVENT.REMOTE_USER_LEAVE, event => {
      const { playerList } = event.data;
      page.playerList = playerList;
      console.log(logkey, '* room REMOTE_USER_LEAVE', event);
    });
    // 远端用户推送视频
    this.trtc.on(TRTC_EVENT.REMOTE_VIDEO_ADD, event => {
      console.log(logkey, '* room REMOTE_VIDEO_ADD', event);
      const { player } = event.data;
      let playerList = this.trtc.setPlayerAttributes(player.id, {
        muteVideo: false
      });
      page.playerList = playerList
    });
    // 远端用户推送音频
    this.trtc.on(TRTC_EVENT.REMOTE_AUDIO_ADD, event => {
      console.log(logkey, '* room REMOTE_AUDIO_ADD', event);
      const { player } = event.data;
      let playerList = this.trtc.setPlayerAttributes(player.id, { muteAudio: false })
      page.playerList = playerList
    });
    // 远端用户取消推送视频
    this.trtc.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, event => {
      console.log(logkey, '* room REMOTE_VIDEO_REMOVE', event);
      const { player } = event.data;
      //this.trtc.setPlayerAttributesHandler(player, { muteVideo: true })
    });
    // 远端用户取消推送音频
    this.trtc.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, event => {
      console.log(logkey, '* room REMOTE_AUDIO_REMOVE', event);
      const { player } = event.data;
    });
  },
  // #endif


  start(page, sdkAppId=uni.$x.tcloud.sdkAppId, userId=uni.$x.tcloud.userId, userSig=uni.$x.tcloud.userSig) {
    console.log(logkey, 'start')
    this.userId = this.userId || userId
    this.userSig = this.userSig || userSig
    this.sdkAppId = this.sdkAppId || sdkAppId

    // #ifdef APP-PLUS
    this.trtcApp = TrtcApp.createInstance()
    this.trtcApp.on("onRemoteUserEnterRoom", (userId) => {
      console.log(`${logkey} onRemoteUserEnterRoom userId = ${userId}`)
    })
    this.trtcApp.on("onUserVideoAvailable", (res) => {
      const { userId, available } = res;
      console.log(`${logkey} onUserVideoAvailable userId = ${userId} available=${available}`)
      if(available) page.playerList.push({userId, streamID: userId, id: userId})
      setTimeout(()=>this.trtcApp.startRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeBig, userId), 2000)
    })
    this.trtcApp.on("onEnterRoom", (result) => {
      console.log(`${logkey} onEnterRoom: ${result}ms`)
    })
    this.trtcApp.on("onExitRoom", (reason) => {
      console.log(`${logkey} onExitRoom: ${reason}`)
    })
    this.trtcApp.on('onWarning', (res) => {
      console.log(`${logkey} onWarning`, res)
    })
    this.trtcApp.on('onError', (res) => {
      console.log(`${logkey} onError`, res)
    })
    this.trtcApp.on('onFirstVideoFrame', (res) => {
      console.log(`${logkey} onFirstVideoFrame`, res)
    })
    console.log(logkey, 'start end')
    // #endif

    // #ifdef MP-WEIXIN
    this.trtc = new TRTCWX(page)
    page.trtcHandleEvent = (type, event)=>{
      if(type==='pusherStateChangeHandler') {
        this.trtc.pusherEventHandler(event)
      }else if(type==='pusherNetStatusHandler') {
        this.trtc.pusherNetStatusHandler(event)
      }else if(type==='pusherErrorHandler') {
        console.error('pusher error', event)
        this.trtc.pusherErrorHandler(event)
      }else if(type==='pusherBGMStartHandler') {
        this.trtc.pusherBGMStartHandler(event)
      }else if(type==='pusherBGMProgressHandler') {
        this.trtc.pusherBGMProgressHandler(event)
      }else if(type==='pusherBGMCompleteHandler') {
        this.trtc.pusherBGMCompleteHandler(event)
      }else if(type==='pusherAudioVolumeNotify') {
        this.trtc.pusherAudioVolumeNotify(event)
      }else if(type==='playerStateChange') {
        this.trtc.playerEventHandler(event)
      }else if(type==='playerFullscreenChange') {
        this.trtc.playerFullscreenChange(event)
      }else if(type==='playerNetStatus') {
        this.trtc.playerNetStatus(event)
      }else if(type==='playerAudioVolumeNotify') {
        this.trtc.playerAudioVolumeNotify(event)
      }else {
        console.log(logkey, 'no event handler', type)
      }
    }
    page.pusher = this.trtc.createPusher({
      sdkAppID: this.sdkAppId,
      userID: this.userId,
      autoPush: false,
      userSig: this.userSig,
    }).pusherAttributes

    console.log(logkey, 'pusher', page.pusher)
    // #endif
  },
  ready(page){
    console.log(logkey, 'ready')

    // #ifdef MP-WEIXIN
    this.bindTRTCRoomEvent(page)
    // #endif
  },


  enterRoom(options = {}) {
    console.log(logkey, 'enterRoom1', options)

    let  {
      page,
      roomId,
      audio = true,
      video = true,
      videoProfile = '480p',
      trtcEl = 'trtc-el-',
      elLocal = 'trtc-el-local',
      elRemote = 'trtc-el-remote',
      fail,
      onLocal,
      onRemote,
      debugMode = false, 
      useStringRoomId = true,
      readonly = false,
      mode = 'rtc',
      // streamId = '', // 添加streamId参数用于自动旁路转推
    } = options

    // #ifdef APP-PLUS
    let appParams = {
      sdkAppId: this.sdkAppId,
      userId: this.userId,
      userSig: this.userSig,
      roomId: 0,
      strRoomId: roomId,
      role: TRTCRoleType.TRTCRoleAnchor,
      // streamId: streamId, // 添加streamId用于自动旁路转推
    }
    console.log(logkey, 'enterRoom', JSON.stringify(appParams))
    this.trtcApp.enterRoom(appParams, TRTCAppScene.TRTCAppSceneVideoCall); 
    this.trtcApp.startLocalPreview(true, this.userId)
    this.trtcApp.startLocalAudio()
    console.log(logkey, 'enterRoom end')
    // #endif

    // #ifdef XT_PC || H5
    this.playerList = []
    let params = {
      mode,
      sdkAppId: this.sdkAppId,
      userId: this.userId,
      userSig: this.userSig,
      // streamId: streamId, // 添加streamId用于自动旁路转推
    }
    if(useStringRoomId!==undefined) params.useStringRoomId = useStringRoomId
    this.client = TRTC.createClient(params)
    this.client.on('stream-added', event => {
      console.log(logkey, 'stream-added')
      const remoteStream = event.stream
      this.client.subscribe(remoteStream)
    })
    this.client.on('stream-subscribed', event => {
      console.log(logkey, 'stream-subscribed')
      const remoteStream = event.stream
      console.log(logkey, 'stream:', remoteStream.getUserId())
      if (!this.playerList.find(v => v.getUserId() === remoteStream.getUserId())) {
        remoteStream.userID = remoteStream.getUserId()
        this.playerList.push(remoteStream)
      }
      remoteStream.play(trtcEl+remoteStream.getUserId()).catch(error => {
        console.error(logkey, 'remote stream play', error)
        this.handleFail()
        if (fail) fail(error)
      })
      remoteStream.on('error', error => {
        console.error(logkey, 'remote stream error', error)
        this.handleFail()
        if (fail) fail(error)
        const errorCode = error.getCode()
        if (errorCode === 0x4043) {
          console.error('PLAY_NOT_ALLOWED');
          // PLAY_NOT_ALLOWED,引导用户手势操作并调用 stream.resume 恢复音视频播放
          // stream.resume()
        }
      })
      if (onRemote) onRemote(this.localStream, this.playerList)
    })

    return this.client.join({ roomId }).then(() => {
      this.localStream = TRTC.createStream({ userId: this.userId, audio, video })
      this.localStream.setVideoProfile(videoProfile)
      if(readonly) return Promise.resolve()
      return this.localStream.initialize().then(() => {
        if (onLocal) onLocal(this.localStream, this.playerList)
        
        return this.localStream.play(trtcEl+this.userId).then(()=>{
          return this.client.publish(this.localStream).then(res=>{
            console.log(logkey, 'start push')
            return res
          })
        })
      }).catch(error => {
        console.error(logkey, 'local stream initialize', error)
        this.handleFail()
        if (fail) fail(error)
      })
    })
    // #endif


    // #ifdef MP-WEIXIN
    let params1 = {
      scene: mode,
      // autopush: true,
      sdkAppID:this.sdkAppId, // 您的腾讯云账号
      userID:this.userId, //当前进房用户的userID
      userSig: this.userSig, // 您服务端生成的userSig
      // roomID: roomId, // 您进房的房间号，
      enableMic: !readonly && audio, // 进房默认开启音频上行
      enableCamera: !readonly && video, // 进房默认开启视频上行
      debugMode, 
      // useStringRoomId,
      // streamId: streamId, // 添加streamId用于自动旁路转推
    }
    if(useStringRoomId!==undefined&&useStringRoomId!==null) params1.useStringRoomId = useStringRoomId
    params1[useStringRoomId?'strRoomID':'roomID'] = roomId
    let pusherData = this.trtc.enterRoom(params1)
    // let pusherData = this.trtc.enterRoom(params1,TRTCAppScene.TRTCAppSceneLIVE)

    page.pusher = pusherData

    // if(!readonly) {
    setTimeout(()=>{
      this.trtc.getPusherInstance().start()
      console.log(logkey, 'start push')
    }, 1000)
    // }

    console.log(logkey, 'pusher', page.pusher)
    // #endif
  },
  leaveRoom(options={}) {
    console.log(logkey, 'leaveRoom')

    let { page } = options

    // #ifdef XT_PC || H5
    if (!this.client) return Promise.resolve()
    return this.client.leave().then(() => {
      this.playerList = []
      this.localStream.stop()
      this.localStream.close()
      this.localStream = null
      this.client = null
    })
    // #endif


    // #ifdef MP-WEIXIN
    const result = this.trtc.exitRoom()
    page.pusher = null
    page.playerList = []
    return Promise.resolve()
    // #endif

    // #ifdef APP-PLUS
    if (this.trtcApp) {
      this.trtcApp.stopLocalPreview()
      this.trtcApp.stopLocalAudio()
      page.playerList.forEach(userId=>{
        this.trtcApp.stopRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeBig)
      })
      this.trtcApp.exitRoom()
      TrtcApp.destroyInstance()
      this.trtcApp = null
    }
    // #endif
  },

  handleFail() {
    // #ifdef XT_PC || H5
    this.client&&this.client.leave()
    this.playerList = []
    this.localStream&&this.localStream.stop()
    this.localStream&&this.localStream.close()
    this.localStream = null
    this.client = null
    // #endif
  }
}

export default function ($x, {
  trtcExtend
} = {}, app) {
  Object.assign(trtc, trtcExtend || {})
  $x.trtc = trtc
}